package com.sinszm.web.interceptor;

import com.google.gson.Gson;
import com.sinszm.common.util.CommonUtils;
import com.sinszm.web.support.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 访问拦截器
 *
 * @author chenjianbo
 */
public class MRequestInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(MRequestInterceptor.class);

    private static final String CURRENT_TIME = "_request_tag";

    private Gson gson;

    public MRequestInterceptor(Gson gson) {
        this.gson = gson;
    }

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) {
        logger.info(">>[{}]>> started >>>>>>>>>>>>>>>>>>>>>>>>>>>>", request.getRequestURI());
        Long currentTime = System.currentTimeMillis();
        request.setAttribute(CommonUtils.SHA1(CURRENT_TIME), currentTime);
        return true;
    }

    @Override
    public void afterCompletion(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler, Exception ex) {
        String host = request.getRemoteHost();
        String uri = request.getRequestURI();
        String method = request.getMethod();
        String params = requestParams(request);
        Long currentTime = (Long) request.getAttribute(CommonUtils.SHA1(CURRENT_TIME));
        logger.info(
                "请求地址:{}, 路径:{}, 请求方式:{}, 请求耗时:{}毫秒, 请求参数：[ {} ] ",
                host,
                uri,
                method,
                currentTime == null ? -1L : System.currentTimeMillis() - currentTime,
                params
        );
        logger.info(">>[{}]>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", uri);
    }

    private String requestParams(HttpServletRequest request) {
        switch (request.getMethod()) {
            case "POST":
                return gson.toJson(RequestUtils.requestParams(request)) +
                        " @@@ " +
                        gson.toJson(RequestUtils.requestBody(request));
            case "GET":
            default:
                return gson.toJson(RequestUtils.requestParams(request));
        }
    }

}